package cn.com.org.base;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import cn.com.common.tools.CookieUtil;
import cn.com.org.dao.RedisUtil;
import cn.com.org.service.Common;

public class Basefilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		//System.out.println("init-------");
	}

	@Override
	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {

		HttpServletResponse responseh = (HttpServletResponse) servletResponse;
		HttpServletRequest requesth = (HttpServletRequest) servletRequest;
		String uri = requesth.getRequestURI().replaceFirst(
				requesth.getContextPath(), "");
		if (uri.indexOf(".") > 0 && !uri.endsWith("jsp")
				|| uri.indexOf("login") >= 0) {
			filterChain.doFilter(servletRequest, servletResponse);//
			return;
		}

		String lcname = CookieUtil.getCookie(requesth, "lcname");
		String accesskey = CookieUtil.getCookie(requesth, "accesskey");
        
		if ((lcname == null || lcname.isEmpty())) {
			responseh.sendRedirect(requesth.getContextPath() + "/login");
			return;
		}

		RedisUtil uinfo = new RedisUtil();

		String uaccess = uinfo.getValue(lcname);
		if (uaccess == null || !uaccess.equals(accesskey)) {
			responseh.sendRedirect(requesth.getContextPath() + "/login");
			return;
		}
		uinfo.setValue(lcname, accesskey,30);
		filterChain.doFilter(servletRequest, servletResponse);//

	}

	@Override
	public void destroy() {

	}

}
